<?php
namespace api\modules\ua\models;

use Yii;
use yii\db\ActiveRecord;
use yii\db\Exception;
use yii\web\IdentityInterface;

class User extends ActiveRecord implements IdentityInterface
{
    public static function getDb(){return Yii::$app->ua;}
    public static function tableName(){return 'user';}

    public function fields()
    {
        return [
            'id',
            'access_token',
            'role',
            'nickname',
            'status'
        ];
    }

    //创建用户（微信小程序专用）
    public function create($json)
    {
        //绑定了开发者账号才能获取unionid
//        $this->unionid    = isset($json->unionid)?$json->unionid:null;
        $this->session_key  = $json->session_key;
        $this->access_token = $json->access_token;
        $this->status       = 0;

        try{
            if(!$this->save()){throw new Exception;}else{return $this;}
        }catch (Exception $e){
            $data['code']=10001;return $data;
        }
    }

    //设置缓存
    public static function setSession($prefix, $token, $session_key)
    {
        $cache      = yii::$app->cache;
        $cache->set($prefix.'_'.$token, $session_key, 7200);
    }

    //获取缓存
    public static function getSession($prefix, $key)
    {
        $cache      = yii::$app->cache;
        return $cache->get($prefix.'_'.$key);
    }

    //删除缓存
    public static function deleteSession($prefix, $key)
    {
        $cache      = yii::$app->cache;
        return $cache->delete($prefix.'_'.$key);
    }

    //根据Token获取用户数据
    public static function getUserByToken($token)
    {
        return User::find()->where(['access_token'=>$token])->one();
    }

    //根据openid获取用户数据
    public static function getUserByOpenId($openid)
    {
        return User::find()->where(['openid'=>$openid])->one();
    }

    //根据用户ID获取用户数据
    public static function getUserById($id)
    {
        return User::find()->where(['id'=>$id])->one();
    }


    //异常处理
    public static function getModelError($model){
        $errors = $model->getErrors();
        if(!is_array($errors)) return '';
        $firstError = array_shift($errors);
        if(!is_array($firstError)) return '';
        return array_shift($firstError);
    }

    /*
     * 以下几个方法是验证用户是否登录
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id]);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    public function getAuthKey()
    {
        return $this->auth_key;
    }

    public function loginByAccessToken($token, $type) {
        return static::findIdentityByAccessToken($token, $type);
    }

    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    public function getId()
    {
        return $this->getPrimaryKey();
    }
}
